/*
	Respawn Vehicle

	Respawns an empty vehicle under following circumstances:
	- the vehicle is damaged (see _max_damage)
	- the vehicle was moved away and left alone for more than 20 minutes
	- the vehicle is damaged at start position

	USAGE:
	[vehicle, delay] execVM "scripts\respawn_vehicle.sqf";

	EXAMPLE: (vehicle init expression)
	[this, 1] execVM "scripts\respawn_vehicle.sqf";
*/

private ["_vehicle", "_delay", "_start_pos", "_start_dir", "_type", "_moved", "_empty","_idle", "_respawn", "_max_idle", "_max_distance", "_max_damage"];

if (!isServer) exitWith{};

_vehicle = _this select 0;
_delay = _this select 1;
_start_pos = getPos _vehicle;
_start_dir = getDir _vehicle;
_type = typeOf _vehicle;
_idle = 0;
_max_idle = 4800;
_max_distance = 10;
_max_damage = 0.6;
_respawn = false;

_delay = _delay * 5;

while {true} do {
	sleep _delay;
	if (({alive _x} count (crew _vehicle)) == 0) then {
		// vehicle is empty
		_moved = (if (_vehicle distance _start_pos > _max_distance) then {true} else {false});
		if ((damage _vehicle > 0) && !_moved) then {
			// vehicle is damaged at start_pos
			_respawn = true;
		};
		if (damage _vehicle > _max_damage || !(alive _vehicle)) then {
			// vehicle is damaged
			_respawn = true;
		};
		if (_moved) then {
			// vehicle is idle and not at start position
			_idle = _idle + _delay;
			if (_idle > _max_idle) then {
				// vehicle has been idle for too long
				_respawn = true;
				_idle = 0;
			};
		};
		if (_respawn) then {
			// delete and respawn vehicle at start position
			deleteVehicle _vehicle;
			sleep 0.5;
			_vehicle = _type createvehicle _start_pos;
			_vehicle setpos _start_pos;
			_vehicle setdir _start_dir;
			if (!isNil "verbose") then {
				hintSilent format ["a %1 respawned at airbase", typeOf _vehicle];
			};
			_respawn = false;
		};
	} else {
		_idle = 0;
	};
};
